import { readFile, writeFile, mkdir } from 'fs/promises'
import { join } from 'path'

// const baseUrl = import.meta.url

async function buildInline() {
  try {
    // 确保 dist 目录存在
    await mkdir('dist', { recursive: true })

    // 1. 读取原始 HTML 文件
    const htmlTemplate = await readFile('./index.html', 'utf-8')

    // 2. 编译 TypeScript 到 JavaScript
    const buildResult = await Bun.build({
      entrypoints: ['./game.ts'],
      minify: true,
      sourcemap: 'none',
      target: 'browser',
    })

    if (!buildResult.success) {
      console.error('构建 JavaScript 失败:', buildResult.logs)
      return
    }

    // 获取编译后的 JavaScript 内容
    const jsBundle = await buildResult.outputs[0].text()

    // 3. 编译 Sass 到 CSS
    const sassProcess = Bun.spawnSync(['sass', './game.scss'])
    let cssContent = ''

    if (sassProcess.exitCode === 0) {
      cssContent = sassProcess.stdout.toString()
    } else {
      console.error('Sass 编译失败:', sassProcess.stderr.toString())
    }

    // 4. 替换 HTML 中的内容
    let finalHtml = htmlTemplate
      // 替换标题
      .replace('<title>Document</title>', '<title>2048 Game</title>')
      // 内联 CSS
      .replace('<link rel="stylesheet" href="./game.scss" />', `<style>${cssContent}</style>`)
      // 内联 JavaScript
      .replace('<script src="./game.ts"></script>', `<script>${jsBundle}</script>`)

    // 5. 写入最终文件
    const outputPath = join('dist', '2048.html')
    await writeFile(outputPath, finalHtml)

    console.log(`✅ 成功生成文件: ${outputPath}`)
    console.log(`📦 文件大小: ${(finalHtml.length / 1024).toFixed(2)} KB`)
  } catch (error) {
    console.error('❌ 构建过程中出现错误:', error)
  }
}

buildInline()
